package com.seari.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.seari.bean.DeviceOfServer;
import com.seari.bean.DeviceOfSwitch;
import com.seari.bean.MonitorDevice;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.mapper.MonitorMapper;
import com.seari.service.MonitorService;

import redis.clients.jedis.Jedis;

@Service("MonitorService")
public class MonitorServiceImpl implements MonitorService
{
	private static HashMap<String, String> monitorServerKeyMap;
	private static String[] serverKeys;
	private static HashMap<String, String> monitorSwitchKeyMap;
	private static String[] switchKeys;
	
	@Autowired
	private MonitorMapper monitorMapper;

	//获取服务器资源排行
	@Override
	public Map<String, List<Map<String, String>>> getDeviceOfComputerByTop(int count)
	{
		// TODO Auto-generated method stub
		Jedis jedis = null;
		Map<String, List<Map<String, String>>> result = null;
		try
		{
			
			jedis = JedisUtilProxy.getJedis();
			List<String> resultList = jedis.hmget("device_status", serverKeys); //从REDIS HASH中获取相关设备的信息
			if(CollectionUtils.isNotEmpty(resultList))
			{
				List<DeviceOfServer> deviceList = new ArrayList<>();
				for (String objString : resultList)
				{
					if(StringUtils.isBlank(objString))continue;
					DeviceOfServer deviceOfServer = JSON.parseObject(objString, DeviceOfServer.class);
					deviceOfServer.setServerNameCn(monitorServerKeyMap.get(deviceOfServer.getDeviceName()));//设置设备中文名，方便前台页面使用
					deviceList.add(deviceOfServer);
				}
				result = new HashMap<>();
				result.put("CPU",sortDeviceOfServerByCpuLoad(deviceList, count)); //根据CPU负载排序
				result.put("MEMORY",sortDeviceOfServerByMemoryLoad(deviceList, count)); //根据内存负载排序
				result.put("DISK",sortDeviceOfServerByDiskLoad(deviceList, count)); //根据硬盘负载排序
				result.put("FLOW",sortDeviceOfServerByFlow(deviceList, count)); //根据流量排序
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally
		{
			JedisUtilProxy.close(jedis);
		}
		return result;
	}
	
	private List<Map<String, String>> sortDeviceOfServerByCpuLoad(List<DeviceOfServer> deviceOfServers,int count)
	{
		List<Map<String, String>> resultList = new ArrayList<>();
		//根据CPU负载逆序排序
		List<DeviceOfServer> sortedList = deviceOfServers.stream().sorted(Comparator.comparing(DeviceOfServer::getResultCpuLoad).reversed()).collect(Collectors.toList());
		for(int i = 0 ; i < sortedList.size() && i < count; i++) 
		{
			Map<String, String> resultMap =new HashMap<>();
			resultMap.put(sortedList.get(i).getServerNameCn(), sortedList.get(i).getResultCpuLoad() + "");
			resultList.add(resultMap);
		}
		return resultList;
	}
	
	private List<Map<String, String>> sortDeviceOfServerByMemoryLoad(List<DeviceOfServer> deviceOfServers,int count)
	{
		List<Map<String, String>> resultList = new ArrayList<>();
		//根据内存负载逆序排序
		List<DeviceOfServer> sortedList = deviceOfServers.stream().sorted(Comparator.comparing(DeviceOfServer::getResultMemoryUsage).reversed()).collect(Collectors.toList());
		for(int i = 0 ; i < sortedList.size() && i < count; i++) 
		{
			Map<String, String> resultMap =new HashMap<>();
			resultMap.put(sortedList.get(i).getServerNameCn(), sortedList.get(i).getResultMemoryUsage() + "");
			resultList.add(resultMap);
		}
		return resultList;
	}
	
	private List<Map<String, String>> sortDeviceOfServerByDiskLoad(List<DeviceOfServer> deviceOfServers,int count)
	{
		List<Map<String, String>> resultList = new ArrayList<>();
		//根据硬盘负载逆序排序
		List<DeviceOfServer> sortedList = deviceOfServers.stream().sorted(Comparator.comparing(DeviceOfServer::getResultDiskUsage).reversed()).collect(Collectors.toList());
		for(int i = 0 ; i < sortedList.size() && i < count; i++) 
		{
			Map<String, String> resultMap =new HashMap<>();
			resultMap.put(sortedList.get(i).getServerNameCn(), sortedList.get(i).getResultDiskUsage() + "");
			resultList.add(resultMap);
		}
		return resultList;
	}
	
	private List<Map<String, String>> sortDeviceOfServerByFlow(List<DeviceOfServer> deviceOfServers,int count)
	{
		//根据流量逆序排序，假数据
		List<Map<String, String>> resultList = new ArrayList<>();
		Map<String, String> resultMap1 =new HashMap<>();
		resultMap1.put(monitorServerKeyMap.get(serverKeys[0]), "63");
		Map<String, String> resultMap2 =new HashMap<>();
		resultMap2.put(monitorServerKeyMap.get(serverKeys[1]), "41");
		Map<String, String> resultMap3 =new HashMap<>();
		resultMap3.put(monitorServerKeyMap.get(serverKeys[2]), "40");
		resultList.add(resultMap1);
		resultList.add(resultMap2);
		resultList.add(resultMap3);
		return resultList;
	}
	
	@Override
	public Map<String, DeviceOfSwitch> getDeviceOfSwitch()
	{
		Jedis jedis = null;
		Map<String, DeviceOfSwitch> resultMap = null;
		try
		{
			jedis = JedisUtilProxy.getJedis();
			List<String> resultList = jedis.hmget("switch_status", switchKeys); //从REDIS HASH中获取相关交换机的信息
			if(CollectionUtils.isNotEmpty(resultList))
			{
				resultMap = new HashMap<>();
				for (String objString : resultList)
				{
					if(StringUtils.isBlank(objString))continue;
					DeviceOfSwitch deviceOfSwitch = JSON.parseObject(objString, DeviceOfSwitch.class);
					resultMap.put(monitorSwitchKeyMap.get(deviceOfSwitch.getDeviceName()), deviceOfSwitch);
				}
			}
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JedisUtilProxy.close(jedis);
		}
		return resultMap;
	}
	
	@Override
	public List<Map<String, String>> getDeviceByCpu()
	{
		// TODO Auto-generated method stub
		List<Map<String, String>> result = null;
		Jedis jedis = null;
		try
		{
			jedis = JedisUtilProxy.getJedis();
			List<String> resultList = jedis.hmget("device_status", serverKeys); //从REDIS HASH中获取相关设备的信息
			if(CollectionUtils.isNotEmpty(resultList))
			{
				List<DeviceOfServer> deviceList = new ArrayList<>();
				for (String objString : resultList)
				{
					if(StringUtils.isBlank(objString))continue;
					DeviceOfServer deviceOfServer = JSON.parseObject(objString, DeviceOfServer.class);
					deviceOfServer.setServerNameCn(monitorServerKeyMap.get(deviceOfServer.getDeviceName()));//设置设备中文名，方便前台页面使用
					deviceList.add(deviceOfServer);
				}
				result = sortDeviceOfServerByCpuLoad(deviceList, Integer.MAX_VALUE);
			}
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JedisUtilProxy.close(jedis);
		}
		return result;
	}

	@Override
	public List<MonitorDevice> getMonitorDeviceList()
	{
		// TODO Auto-generated method stub
		return monitorMapper.getMonitorDeviceList();
	}
	
	@Override
	public List<MonitorDevice> getSwitchDeviceList()
	{
		// TODO Auto-generated method stub
		return monitorMapper.getSwitchDeviceList();
	}
	
	
	@PostConstruct
	public void init()
	{
		//服务器设备
		List<MonitorDevice> monitorDevices = getMonitorDeviceList();
		if(CollectionUtils.isNotEmpty(monitorDevices))
		{
			serverKeys = new String[monitorDevices.size()];//初始化key列表
			monitorServerKeyMap = new HashMap<>(); //初始化Device key与服务器中文名键值对
			for(int i = 0; i < monitorDevices.size(); i++)
			{
				serverKeys[i] = monitorDevices.get(i).getKeyName();
				monitorServerKeyMap.put(monitorDevices.get(i).getKeyName(), monitorDevices.get(i).getServerNameCn());
			}
		}
		//交换机设备
		List<MonitorDevice> switchDevices = getSwitchDeviceList();
		if(CollectionUtils.isNotEmpty(switchDevices))
		{
			switchKeys = new String[switchDevices.size()];//初始化key列表
			monitorSwitchKeyMap = new HashMap<>(); //初始化Device key与交换机中文名键值对
			for(int i = 0; i < switchDevices.size(); i++)
			{
				switchKeys[i] = switchDevices.get(i).getKeyName();
				monitorSwitchKeyMap.put(switchDevices.get(i).getKeyName(), switchDevices.get(i).getServerNameCn());
			}
		}
	}

	@Override
	public List<Map<String, Object>> getDeviceAllStatus() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		Jedis jedis = null;
		try
		{
			jedis = JedisUtilProxy.getJedis();
			List<String> resultList = jedis.hmget("etStatus", serverKeys); //从REDIS HASH中获取相关设备的信息
			
			if(CollectionUtils.isNotEmpty(resultList))
			{
				Map<String, Object> hashMap = new HashMap<String,Object>();;
				//List<DeviceOfServer> deviceList = new ArrayList<>();
				for (String objString : resultList)
				{
					if(StringUtils.isBlank(objString))continue;
					DeviceOfServer deviceOfServer = JSON.parseObject(objString, DeviceOfServer.class);
					hashMap.put(monitorServerKeyMap.get(deviceOfServer.getDeviceName()), deviceOfServer);
					
				}
	            Set entrySet = hashMap.entrySet();
	            Iterator it2 = entrySet.iterator();
	            while (it2.hasNext()) {
	                Map<String, Object> item = new HashMap<String, Object>();
	                Entry m = (Entry) it2.next();
	                item.put("name", (String) m.getKey());
	                item.put("value", m.getValue());
	                result.add(item);
	            }
				
			}
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JedisUtilProxy.close(jedis);
		}
		return result;
	}

	

}
